﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WindowsService.BusinessServices;
using WindowsService.Common;

namespace WindowsService
{
    public partial class StartService : ServiceBase
    {
        /// <summary>
        /// 当前服务是否停止（默认时flase）
        /// </summary>
        private bool isStop = false;

        /// <summary>
        /// 启动服务
        /// </summary>
        public StartService()
        {
            InitializeComponent();

            this.CanPauseAndContinue = true;
            this.CanStop = true;
            isStop = false;
        }

        ///<summary>
        ///暂停服务
        ///</summary>
        protected override void OnPause()
        {
            LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, "\r\n\r\n.....暂停服务.....\r\n\r\n"));
            isStop = true;  //服务暂停
        }

        ///<summary>
        ///恢复服务
        ///</summary>
        protected override void OnContinue()
        {
            LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, "\r\n\r\n.....继续服务.....\r\n\r\n"));
            isStop = false; //继续服务
        }

        /// <summary>
        /// 服务停止
        /// </summary>
        protected override void OnStop()
        {
            LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, "\r\n\r\n.....停止服务.....\r\n\r\n"));
            isStop = true;  //服务停止
        }

        /// <summary>
        /// 服务开始运行
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            try
            {
                //当服务没有停止时，开始具体业务
                if (isStop == false)
                {
                    Thread thread = new Thread(new ThreadStart(new TaskStart().TaskProcessing));
                    thread.Start();
                }
            }
            catch (Exception ce)
            {
                LogHelper.Write("Error", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), ce, "\r\n\r\n.....停止服务.....\r\n\r\n"));
            }
        }
    }
}
